import 'dart:convert';

import 'package:appinio_swiper/appinio_swiper.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nfc_kit/flutter_nfc_kit.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'package:get/get.dart';
import 'package:memorize_words/util/ImageButton.dart';

import '../../../../store/setting_store.dart';
import '../../../../util/EasyInput.dart';
import '../../../../util/SwipeCard.dart';
import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {

  //  下拉菜单单元
  _buildPopupMenuItem(IconData iconName, String title) {
    return Column(
      children: [
        Row(
          children: <Widget>[
            Icon(iconName, size: 22.0, color: Colors.black),
            const SizedBox(width: 12.0),
            Text(title, style: const TextStyle(color: Colors.black)),
          ],
        ),
      ],
    );
  }
  //  下拉菜单
  List<PopupMenuEntry> getPopupList() {
    return [
      PopupMenuItem(
        child: _buildPopupMenuItem(Icons.book_outlined, "切换词典"),
        value: 'select_book',
      ),
      const PopupMenuDivider(height: 1.0),
      PopupMenuItem(
        child: _buildPopupMenuItem(Icons.flip, "扫一扫"),
        value: 'qr_code',
      ),
      PopupMenuItem(
        child: _buildPopupMenuItem(Icons.cast_connected, "NFC"),
        value: 'nfc_code',
      ),
    ];
  }

  // 展示读取NFC弹框
  void showReadDialog() async {
    TextEditingController nfcEditing = TextEditingController();
    bool isBack = false;

    Get.defaultDialog(
      title: '读取NFC',
      radius: 8.0,
      barrierDismissible: false,
      content: Column(
        children: [
          const Text(
            '将手机感应区贴近NFC标签感应',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 15),
          ),
          const SizedBox(height: 8.0),
          Padding(
            padding: const EdgeInsets.fromLTRB(35.0, 5.0, 35.0, 0.0),
            child: TextField(
              controller: nfcEditing,
              decoration: InputDecoration(
                border: InputBorder.none,
                fillColor: Colors.grey[100],
                filled: true,
              ),
            ),
          ),
        ],
      ),
      cancel: TextButton(
        onPressed: () {
          Get.back();
          isBack = true;
        },
        child: const Text(
          '退出',
          style: TextStyle(fontSize: 18.0),
        ),
      ),
    );

    do {
      // 扫描NFC卡
      try {
        NFCTag tag = await FlutterNfcKit.poll(timeout: const Duration(days: 1));
        nfcEditing.text = tag.id;
        // print('扫描结果：${tag.id}');
      } catch (e) {
        // print('Scan Error: $e');
      }
    } while (!isBack);
  }

  AppinioSwiperController swiperController = AppinioSwiperController();
  SettingStore _settingStore = SettingStore();

  Future<void> previousOne() async {
    int wordSelected = await _settingStore.getWordSelected();
    if (wordSelected <= 0) {
      await _settingStore.setWordSelected(0);
      Fluttertoast.showToast(
        msg: "前面没有单词啦！",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0,
      );
    } else {
      await _settingStore.setWordSelected(wordSelected - 1);
    }
  }
  Future<void> nextOne() async {
    int wordSelected = await _settingStore.getWordSelected();
    await _settingStore.setWordSelected(wordSelected + 1);
  }
  Future<void> _swipe(int index, AppinioSwiperDirection direction) async {
    if (direction.name.toString() == 'right' ) {
      await previousOne();
    } else if (direction.name.toString() == 'left'){
      await nextOne();
    }
    await controller.onInit();
    // print("the card was swiped to the: " + direction.name);
  }

  void _unswipe(bool unswiped) {
    if (unswiped) {
      print("SUCCESS: card was unswiped");
    } else {
      print("FAIL: no card left to unswipe");
    }
  }

  void _onEnd() {
    print("end reached!");
  }

  String truncateString(String text, int maxLength) {
    if (text.length <= maxLength) {
      return text;
    } else {
      return text.substring(0, maxLength) + '...';
    }
  }

  void createBox(context) async {
    Get.defaultDialog(
      title: '新增笔记',
      radius: 10.0,
      barrierDismissible: false,
      content: Container(
        decoration: BoxDecoration(
            color: Colors.white60,
            border: Border.all(color: Colors.black12, width: 1),
            borderRadius: BorderRadius.circular((10.0))),
        child: Padding(
          padding: const EdgeInsets.all(5.0),
          child: Column(
            children: [
              // name,pic,desc,typ,date,personBy,userBy
              Container(
                  // padding: const EdgeInsets.fromLTRB(13, 0, 10, 0),
                  // decoration: const BoxDecoration(
                  //   borderRadius: BorderRadius.all(Radius.circular(15)),
                  //   color: Color(0xFFF2F3F7),
                  // ),
                  child: Column(
                    children: [
                      EasyInput(
                        value: controller.val.text,
                        keyboardType: "text",
                        title: "内容",
                        hintText: "请输入内容：",
                        maxLines: 2,
                        values: (value) {
                          controller.val.text = value;
                        },
                      ),
                      EasyInput(
                        value: controller.desc.text,
                        keyboardType: "text",
                        title: "说明",
                        hintText: "请输入说明：",
                        values: (value) {
                          controller.desc.text = value;
                        },
                      ),
                    ],
                  )
              ),
            ],
          ),
        )
        ,
      ),
      confirm: MaterialButton(
        color: Colors.black,
        textColor: Colors.white,
        child: const Text('确认', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () async {
          Map helpText = await controller.getHelpText();
          helpText['self'].add({"val":controller.val.text,"desc":controller.desc.text});
          controller.wordForm.value["helpText"] = json.encode(helpText);
          await controller.updateWord();
          Get.back();
          await controller.onInit();
        },
      ),
      cancel: MaterialButton(
        color: Colors.white,
        textColor: Colors.black87,
        child: const Text('取消', style: TextStyle(fontSize: 18.0,fontWeight: FontWeight.w600)),
        onPressed: () {
          Get.back();
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        ///leading: IconButton(
        ///  icon: const Icon(Icons.density_medium_sharp),
        ///  onPressed: (){},
        ///),
        elevation: 0,
        backgroundColor: Colors.black87,
        title: const Text('词卡闪记'),
        centerTitle: true,
        actions: [
          PopupMenuButton(
            itemBuilder: (BuildContext context) {
              return getPopupList();
            },
            offset: const Offset(0.0, 55.0),
            elevation: 3.0,
            // color: Colors.lightBlue,
            icon: const Icon(Icons.more_vert, size: 30, color:Colors.white,),
            onSelected: (value) async {
              // print('点击的是$value');
              if (value == 'qr_code') {
                controller.handleScan();
              } else if (value == 'nfc_code') {
                NFCAvailability availability = await FlutterNfcKit.nfcAvailability;
                if (availability == NFCAvailability.not_supported) {
                  Fluttertoast.showToast(
                    msg: "您的设备不支持NFC功能！",
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.CENTER,
                    backgroundColor: Colors.red,
                    textColor: Colors.white,
                    fontSize: 16.0,
                  );
                } else if (availability == NFCAvailability.disabled) {
                  Fluttertoast.showToast(
                    msg: "请先打开NFC功能！",
                    toastLength: Toast.LENGTH_SHORT,
                    gravity: ToastGravity.CENTER,
                    backgroundColor: Colors.red,
                    textColor: Colors.white,
                    fontSize: 16.0,
                  );
                } else {
                  showReadDialog();
                }
              } else if (value == 'select_book') {
                // Get.offNamed('/books');
                Get.toNamed('/books')?.then((value) async {
                  if (value == null) { return; } else {
                    controller.onInit();
                  }
                });
              }
            },
          ),
          const SizedBox(width: 10.0),
        ],
      ),
      body: Container(
          height: double.infinity,
          width: double.infinity,
          padding: const EdgeInsets.fromLTRB(8, 4, 8, 4),
          decoration: const BoxDecoration(
            border:  Border(bottom:BorderSide(width: 1,color: Color(0xffe5e5e5)) ),
          ),
          child: Obx(()=>controller.wordForm.value.isNotEmpty?
          CupertinoPageScaffold(
            child: ListView(
              children: [
                const SizedBox(
                  height: 30,
                ),
                SizedBox(
                  height: MediaQuery.of(context).size.height * 0.65,
                  child: AppinioSwiper(
                    loop: true,
                    swipeOptions: const AppinioSwipeOptions.all(),
                    controller: swiperController,
                    unswipe: _unswipe,
                    onSwiping: (AppinioSwiperDirection direction) async {
                      debugPrint(direction.toString());
                    },
                    onSwipe: _swipe,
                    onEnd: _onEnd,
                    cardsCount: 3,
                    cardsBuilder: (BuildContext context, int index) {
                      return SwipeCard(
                        data: controller.wordForm.value,
                        footStr: "${controller.bookForm.value['name']!=null?truncateString(controller.bookForm.value['name'] + ' · ',15):''}${controller.wordSelected.value+1}/${controller.bookForm.value['num']}"
                      );
                    },
                  ),
                ),
                const SizedBox(
                  height: 15,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  // mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    ImageButton(
                      width: 50,
                      height: 50,
                      radius:50,
                      imgPath: 'assets/images/left.png',
                      showText: false,
                      onTap: () async {
                        await previousOne();
                        await controller.onInit();
                        },
                      onLongPress: (){ }
                    ),
                    // const SizedBox(width: 30,),
                    // ImageButton(
                    //     width: 50,
                    //     height: 50,
                    //     radius:50,
                    //     imgPath: 'assets/images/no.png',
                    //     showText: false,
                    //     onTap: (){},
                    //     onLongPress: (){}
                    // ),
                    // const SizedBox(width: 20,),
                    ImageButton(
                        width: 50,
                        height: 50,
                        radius:50,
                        imgPath: 'assets/images/pen.png',
                        showText: false,
                        onTap: (){ createBox(context); },
                        onLongPress: (){ controller.toEditPage();}
                    ),
                    // const SizedBox(width: 20,),
                    // ImageButton(
                    //     width: 50,
                    //     height: 50,
                    //     radius:50,
                    //     imgPath: 'assets/images/yes.png',
                    //     showText: false,
                    //     onTap: (){},
                    //     onLongPress: (){}
                    // ),
                    // const SizedBox(width: 30,),
                    ImageButton(
                        width: 50,
                        height: 50,
                        radius:50,
                        imgPath: 'assets/images/right.png',
                        showText: false,
                        onTap: () async {
                          await nextOne();
                          await controller.onInit();
                        },
                        onLongPress: (){}
                    ),
                  ],
                )
              ],
            ),
          ):const SizedBox()),
      ),
    );
  }
}
